<script lang="ts" setup>
import { Empty, Field, FloatingBubble, Tag } from 'vant'
import { MaterialApi } from '~/api/MaterialApi'
import { MaterialModel } from '~/model'

const route = useRoute()
const router = useRouter()
const searchInput = useLocalStorage('material-search', '')
const materials = ref([] as MaterialModel[])

interface FilterWithName {
  filter: (item: MaterialModel) => boolean
  name: string
}

const filterArr = ref([
  {
    name: '全部在售',
    filter: x => !x.takenOff,
  },
] as FilterWithName[])
const activeFilterIndex = ref(0)

onMounted(() => {
  MaterialApi.getAll()
    .then((res) => {
      materials.value = res
      materials.value.sort((a, b) => a.id - b.id)

      // 添加分组按钮
      const a = materials.value.map(x => x.group).filter(x => !!x)
      const b = Array.from(new Set(a))
      b.forEach((name) => {
        filterArr.value.push({
          name,
          filter: x => x.group === name && !x.takenOff,
        })
      })
      filterArr.value.push({
        name: '未分组商品',
        filter: x => x.group === '' && !x.takenOff,
      })
      filterArr.value.push({
        name: '下架商品',
        filter: x => x.takenOff,
      })

      // 处理 url query: filter
      const filterFromUrl = route.query.filter
      if (filterFromUrl) {
        activeFilterIndex.value = filterArr.value.findIndex(x => x.name === filterFromUrl)
      }
    })
})

function onClick(row: MaterialModel) {
  router.push(`/materials/detail?id=${row.id}`)
}

function onNew() {
  router.push('/materials/detail?new=1')
}

const materialsFiltered = computed(() => {
  const _search = searchInput.value.toLowerCase()
  // console.warn(filterArr.value)
  // console.warn(activeFilterIndex.value)

  const named = filterArr.value[activeFilterIndex.value]
  if (!named) {
    return []
  }
  const currentFilter = named.filter
  const a = materials.value.filter(currentFilter)
  const filtered = a.filter((x) => {
    return x.name.toLowerCase().includes(_search)
      || x.specification.toLowerCase().includes(_search)
      || x.comment.toLowerCase().includes(_search)
  })
  filtered.sort((a, b) => {
    return a.name.localeCompare(b.name) * 100
      + a.specification.localeCompare(b.specification) * 10
      + a.comment.localeCompare(b.comment) * 1
  })
  return filtered
})

function toggleFilter(index: number) {
  activeFilterIndex.value = index
  router.replace(`${route.path}?filter=${filterArr.value[activeFilterIndex.value].name}`)
}
</script>

<template>
  <div>
    <div mb2 b-rd-1 bg-blue-1>
      <div p2 c-blue>
        商品类型
      </div>
      <div px2>
        <Tag
          v-for="(item, index) in filterArr" :key="index" closable mb2 mr2 size="large" type="primary"
          :plain="activeFilterIndex !== index" @click="toggleFilter(index)"
        >
          <span>{{ item.name }}</span>
        </Tag>
      </div>
    </div>

    <div mb2 b-rd-1 bg-white>
      <Field v-model="searchInput" placeholder="搜索..." bg-transparent />
    </div>

    <div v-if="materialsFiltered.length">
      <table class="lx-table lx-table-large">
        <thead>
          <tr>
            <th>名称</th>
            <th>规格</th>
            <th>单位</th>
            <th>单价</th>
            <th>备注</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in materialsFiltered" :key="item.id" @click="onClick(item)">
            <td>{{ item.name }}</td>
            <td>{{ item.specification }}</td>
            <td>{{ item.unit }}</td>
            <td>{{ item.unitPrice }}</td>
            <td>{{ item.comment }}</td>
          </tr>
        </tbody>
      </table>
      <div v-if="searchInput" p4 text-center text-gray-4>
        <div mb2>
          "{{ searchInput }}" 的搜索结果
        </div>
        <div p2 c-blue @click="searchInput = ''">
          查看所有商品
        </div>
      </div>
    </div>

    <Empty v-else :description="`搜索 \&quot;${searchInput}\&quot; 结果为空`">
      <div p2 c-blue @click="searchInput = ''">
        查看所有商品
      </div>
    </Empty>

    <FloatingBubble icon="plus" bg-green5 @click="onNew" />
  </div>
</template>

<route lang="yaml">
meta:
  title: 物资管理
</route>
